import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button } from '@kernelproxy/ui';
import { useLanguage, useLocalizedLink } from '@kernelproxy/i18n';
import { authService } from '../services/auth';

const VerifyEmail = () => {
  const [loading, setLoading] = useState(true);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState('');
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { language } = useLanguage();
  const { getLink } = useLocalizedLink();

  const userId = searchParams.get('userId');
  const secret = searchParams.get('secret');

  useEffect(() => {
    const verifyEmail = async () => {
      if (!userId || !secret) {
        setError(language === 'zh-CN' ? '无效的验证链接' : 'Invalid verification link');
        setLoading(false);
        return;
      }

      try {
        const result = await authService.verifyEmail(userId, secret);
        if (result.success) {
          setSuccess(true);
        } else {
          setError(result.error?.message || (language === 'zh-CN' ? '邮箱验证失败，链接可能已过期' : 'Email verification failed, link may have expired'));
        }
      } catch (err: any) {
        console.error('Email verification error:', err);
        if (err.message?.includes('Invalid token') || err.message?.includes('invalid secret')) {
          setError(language === 'zh-CN' ? '验证链接已过期或无效' : 'Verification link expired or invalid');
        } else {
          setError(err.message || (language === 'zh-CN' ? '邮箱验证失败' : 'Email verification failed'));
        }
      } finally {
        setLoading(false);
      }
    };

    verifyEmail();
  }, [userId, secret, language]);

  const handleContinue = () => {
    navigate(getLink('/dashboard'));
  };

  const handleResend = async () => {
    setLoading(true);
    setError('');
    
    try {
      const result = await authService.resendVerificationEmail();
      if (result.success) {
        setError('');
        alert(language === 'zh-CN' ? '验证邮件已重新发送' : 'Verification email resent');
      } else {
        setError(result.error?.message || (language === 'zh-CN' ? '发送验证邮件失败' : 'Failed to send verification email'));
      }
    } catch (err: any) {
      console.error('Resend verification error:', err);
      setError(err.message || (language === 'zh-CN' ? '发送验证邮件失败' : 'Failed to send verification email'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center px-4 transition-colors duration-300">
      <div className="text-center max-w-md">
        <a href="https://kernelproxy.com" className="inline-flex items-center justify-center mb-8">
          <span className="text-3xl font-bold text-[#00d4ff]">kernel</span>
          <span className="text-3xl font-bold text-[#0f1c3f] dark:text-white">Proxy</span>
        </a>

        {loading ? (
          <div>
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-[#00d4ff] mb-4"></div>
            <p className="text-gray-900 dark:text-white text-lg">
              {language === 'zh-CN' ? '正在验证邮箱...' : 'Verifying email...'}
            </p>
          </div>
        ) : success ? (
          <div className="bg-white dark:bg-gray-800 p-8 rounded-lg shadow-lg">
            <div className="mb-4">
              <svg className="mx-auto h-16 w-16 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
              {language === 'zh-CN' ? '邮箱验证成功！' : 'Email Verified Successfully!'}
            </h2>
            <p className="text-gray-600 dark:text-gray-400 mb-6">
              {language === 'zh-CN' ? '您的邮箱已成功验证。' : 'Your email has been successfully verified.'}
            </p>
            <Button onClick={handleContinue} fullWidth variant="gradient">
              {language === 'zh-CN' ? '继续使用' : 'Continue'}
            </Button>
          </div>
        ) : (
          <div className="bg-white dark:bg-gray-800 p-8 rounded-lg shadow-lg">
            <div className="mb-4">
              <svg className="mx-auto h-16 w-16 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
              {language === 'zh-CN' ? '验证失败' : 'Verification Failed'}
            </h2>
            <p className="text-red-600 dark:text-red-400 mb-6">{error}</p>
            <div className="space-y-3">
              <Button onClick={handleResend} fullWidth variant="gradient">
                {language === 'zh-CN' ? '重新发送验证邮件' : 'Resend Verification Email'}
              </Button>
              <Button onClick={() => navigate(getLink('/login'))} fullWidth variant="outline">
                {language === 'zh-CN' ? '返回登录' : 'Back to Login'}
              </Button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default VerifyEmail;
